package com.nolon.flange.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.nolon.flange.databinding.ItemProjectBinding
import com.nolon.flange.model.Project
import com.nolon.flange.tools.percent2
import com.nolon.flange.tools.toFriendlyDate

class ProjectAdapter(
    val onMoreClicked: (Project) -> Unit,
    val onProjectLongClicked: (Project) -> Boolean
) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val projects = mutableListOf<Project>()

    fun swapData(projects: List<Project>) {
        this.projects.clear()
        this.projects.addAll(projects)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val binding = ItemProjectBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ProjectViewHolder(binding)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val project = projects[position]
        if (holder is ProjectViewHolder) {
            with(holder.binding) {
//                textNo.text = "${position + 1}#"
                imageMore.setOnClickListener { onProjectLongClicked(projects[position]) }
                layout.setOnClickListener { onMoreClicked(projects[position]) }
//                layout.setOnLongClickListener {onProjectLongClicked(projects[position])  }
                textProjectName.text = project.name
                val digest = StringBuilder()

                digest.append("总共 ${project.flangeTypes} 种法兰")
                digest.append("( ${project.flangeCount} 个)")
                digest.append("，拆分后共计 ${project.flangeCount * 4} 个零件（长料加短料）。")
                if (project.hasSolution) {
                    digest.append("已计算下料方案")
                    digest.append("，需 ${project.rawCount} 条角钢")
                    digest.append("，整体利用率 ${project.usageRate.percent2}")
                    digest.append("。")
                }
                textDigest.text = digest.toString()
                textModifiedDate.text = project.modified.toFriendlyDate
//                textCreatedDate.text = project.created.toFriendlyDate + "创建"
            }
        }
    }

    override fun getItemViewType(position: Int) = PROJECT_ITEM

    override fun getItemCount() = projects.size

    class ProjectViewHolder(val binding: ItemProjectBinding) : RecyclerView.ViewHolder(binding.root)

    companion object {
        const val PROJECT_HEADER = 213
        const val PROJECT_ITEM = 234
    }

}